package com.xb.loan.encryptor.handler.impl;


import com.xb.loan.encryptor.LotteryException;
import com.xb.loan.encryptor.bean.LotteryBean;
import com.xb.loan.encryptor.bean.request.other.QueryUserKeyReq;
import com.xb.loan.encryptor.bean.response.other.QueryUserKeyRep;
import com.xb.loan.encryptor.handler.BussinessHandler;
import com.xb.loan.encryptor.util.Base64Utils;
import com.xb.loan.encryptor.util.Const;
import com.xb.loan.encryptor.util.RSAUtils;
import com.xb.loan.encryptor.util.ToolUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.security.interfaces.RSAKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

public class QueryUserKeyHandler implements BussinessHandler {

	private static Log log = LogFactory.getLog(QueryUserKeyHandler.class);
	// 文件锁
	private static Object lock = new Object();
	
	@Override
	public LotteryBean doBussiness(LotteryBean lotteryBean)
			throws LotteryException {

		QueryUserKeyReq req = (QueryUserKeyReq) lotteryBean;

		log.info("QueryUserKeyHandler get user key start,keyIndex:"
				+ req.getKeyIndex());
		
		String userKeyPath = Const.KEY_PATH + File.separatorChar + "user" + File.separatorChar + req.getKeyIndex();

		String pubKeyPath = userKeyPath + File.separatorChar + "publicKey.txt";
		String priKeyPath = userKeyPath + File.separatorChar + "privateKey.txt";
		
		synchronized (lock) {
			// 如果文件不存，则重新创建文件
			if(!new File(pubKeyPath).exists() || !new File(priKeyPath).exists()){
				
				try {
					
					RSAKey[] keys = RSAUtils.genKeyPair();
					// 公钥
					RSAPublicKey publicKey = (RSAPublicKey) keys[0];
					// 私钥
					RSAPrivateKey privateKey = (RSAPrivateKey) keys[1];
					// 公钥base64字符串
					String pubKeyStr = Base64Utils.encode(publicKey.getEncoded());
					// 保存公钥
					Base64Utils.byteArrayToFile(pubKeyStr.getBytes(), pubKeyPath + ".temp");
					// 保存私钥
					Base64Utils.byteArrayToFile(Base64Utils.encode(privateKey.getEncoded()).getBytes(), priKeyPath + ".temp");
					// 密钥文件改名
					new File(pubKeyPath + ".temp").renameTo(new File(pubKeyPath));
					
					new File(priKeyPath + ".temp").renameTo(new File(priKeyPath));
					
					log.info("QueryUserKeyHandler create user rsa files,path:" + userKeyPath);
				} catch (Exception e) {
					
					log.error("QueryUserKeyHandler create user rsa files have exception,path:" + userKeyPath,e);
				}
			}
		}
		
		String readKeyFile = req.isPrivateKey() ? priKeyPath : pubKeyPath;
		// 读取密钥内容
		byte[] dataContent = ToolUtil.fileToBytes(readKeyFile);
		// 密钥
		String keyContent = dataContent == null ? null : new String(dataContent);
		
		log.info("QueryUserKeyHandler read user rsa files,path:" + readKeyFile + ",content:" + keyContent);
		
		QueryUserKeyRep rep = new QueryUserKeyRep();
		
		rep.setHead(LotteryBean.createHead("704", req.getHead().getGuid()));
		rep.setUserKey(keyContent);
		
		return rep;
	}

}
